package models

import (
	"fmt"
	"gonexample/gone/config"
	"log"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var DB *gorm.DB

// Setup initializes the database instance
func Initialize() {
	var err error
	DB, err = gorm.Open(config.Database.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		config.Database.User,
		config.Database.Password,
		config.Database.Host,
		config.Database.Name))

	if err != nil {
		log.Fatalf("models.Init err: %v", err)
	}

	DB.LogMode(true)
	if config.Server.RunMode == "release" {
		DB.LogMode(false)
	}

	// 更改默认表名即添加前缀或其他
	/* gorm.DefaultTableNameHandler = func(DB *gorm.DB, defaultTableName string) string {
		return config.Database.TablePrefix + defaultTableName
	} */

	// DB.SingularTable(true)

	// 设置连接池
	// 空闲
	DB.DB().SetMaxIdleConns(config.Database.MaxIdle)
	// 打开
	DB.DB().SetMaxOpenConns(config.Database.MaxOpen)
	// 超时
	DB.DB().SetConnMaxLifetime(30 * time.Second)
}
